<?php
 
// array for JSON response
$response = array();
 
// check for required fields
if (isset($_POST['tag']) && isset($_POST['json'])) {
 
    $tag = $_POST['tag'];
    $json = $_POST['json'];
	
	$obj = json_decode($json);
	
	$studentArray = $obj->students;
	
	
	// include db connect class
    require_once __DIR__ . '/db_connect.php';
 
    // connecting to db
    $db = new DB_CONNECT();
	
	if ($tag == 'syncStudents') {
		$done = false;
		for ($i = 0; $i < count($studentArray); $i++) {
			$action = $studentArray[$i]->action;
			$stid = $studentArray[$i]->stid;
			$name = $studentArray[$i]->name;
			$grade = $studentArray[$i]->grade;
			$description = $studentArray[$i]->description;
			
			if ($action == "insert") {
				mysql_query("INSERT INTO students(stid, name, grade, description) VALUES('$stid', '$name', '$grade', '$description')");
			} else if ($action == "delete") {
				mysql_query("DELETE FROM students WHERE stid = '$stid'");
			} else if ($action == "update") {
				mysql_query("UPDATE students SET name = '$name', grade = '$grade', description = '$description' WHERE stid = '$stid'");
			}
			$done = true;
		}
	 
		// check if row inserted or not
		if ($done == true) {
			// successfully inserted into database
			$response["success"] = 1;
			$response["message"] = "Sync successfully.";
	 
			// echoing JSON response
			echo json_encode($response);
		} else {
			if (count($studentArray) >= 1) {
				// failed to insert row
				$response["success"] = 0;
				$response["message"] = "Oops! An error occurred.";
			} else if (count($studentArray) == 0) {
				// failed to insert row
				$response["success"] = -1;
				$response["message"] = "Oops! Database Already Sync.";
			}
			// echoing JSON response
			echo json_encode($response);
		}
	} else if ($tag == 'uploadStudents') {
		$done = false;
		mysql_query("DELETE FROM students");
		for ($i = 0; $i < count($studentArray); $i++) {
			$stid = $studentArray[$i]->stid;
			$name = $studentArray[$i]->name;
			$grade = $studentArray[$i]->grade;
			$description = $studentArray[$i]->description;	
			mysql_query("INSERT INTO students(stid, name, grade, description) VALUES('$stid', '$name', '$grade', '$description')");
			$done = true;
		}
	 
		// check if row inserted or not
		if ($done == true) {
			// successfully inserted into database
			$response["success"] = 1;
			$response["message"] = "Upload successfully.";
	 
			// echoing JSON response
			echo json_encode($response);
		} else {
			// failed to insert row
			$response["success"] = 0;
			$response["message"] = "Oops! An error occurred.";
	 
			// echoing JSON response
			echo json_encode($response);
		}
	}
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}
?>